﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
//using goMatic;
using System.Net;
using System.IO;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using Newtonsoft.Json;
namespace WebService
{
    /// <summary>
    /// Summary description for CCUCMD
    /// </summary>
    [WebService(Namespace = "http://xmlrpc.azurewebsites.net/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class ccucmd : System.Web.Services.WebService
    {

        dbEntities1 oDB = new dbEntities1();

        /// <summary>
        /// Send STATE value to the CCU over the externalIP
        /// </summary>
        /// <param name="sTargetIP">external IP</param>
        /// <param name="sAddress">device ID</param>
        /// <param name="sValueKey"></param>
        /// <param name="valueType"></param>
        /// <param name="value"></param>
        /// <param name="port"></param>
        /// <returns></returns>
        public bool SetValueEx(string sTargetIP, string sAddress, string sValueKey, string valueType, string value, int port)
        {
            try
            {
                string sSetValue = "<?xml version=\"1.0\"?>" +
                    "<methodCall>" +
                      "<methodName>setValue</methodName>" +
                        "<params>" +
                          "<param><value><string>{0}</string></value></param>" +
                          "<param><value><string>{1}</string></value></param>" +
                          "<param><value><{2}>{3}</{2}></value></param>" +
                        "</params>" +
                      "</methodCall>";

                string postString = string.Format(sSetValue, sAddress, sValueKey, valueType, value);
                byte[] postBytes = Encoding.UTF8.GetBytes(postString);

                string sResult = Post(postBytes, port, sTargetIP);

                return true;

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            return false;
        }

        public string GetExternalIP(string CustomerID)
        {
            try
            {
                string sIP = oDB.HMConfig.First(t => t.customerid == CustomerID).external_ip;
                return sIP;
            }
            catch { }

            return "";

        }

        /// <summary>
        /// Get Device details (Rooms/Functions, Displaynames etc.) from the CCU over Port 8181
        /// </summary>
        /// <param name="CCUIP">IP address of the CCU</param>
        /// <returns></returns>
        public string GetDeviceDetailsFromCCU(string CCUIP)
        {
            try
            {
                //Get data from CCU
                string HMQuery = Properties.Settings.Default.getAllDevices;
                WebClient oWeb = new WebClient();
                byte[] bRes = oWeb.UploadData("http://" + CCUIP + ":8181/test.exe", "POST", System.Text.ASCIIEncoding.UTF8.GetBytes(HMQuery));
                string sData = System.Text.ASCIIEncoding.UTF7.GetString(bRes);
                return sData;
            }
            catch (Exception ex)
            {
                return null;
            }
        }


        public static string Init(string sURL, string sID, int port, string targetCCU)
        {
            try
            {
                string sGetValue = "<?xml version=\"1.0\"?>" +
                    "<methodCall>" +
                    "<methodName>init</methodName>" +
                    "<params>" +
                    "<param><value><string>{0}</string></value></param>" +
                    "<param><value><string>{1}</string></value></param>" +
                    "</params>" +
                    "</methodCall>";

                string postString = string.Format(sGetValue, sURL, sID);
                byte[] postBytes = Encoding.UTF8.GetBytes(postString);

                return Post(postBytes, port, targetCCU);

            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }

            return "";
        }

        /// <summary>
        /// Init XML-RPC Service
        /// </summary>
        /// <param name="Interface">BidCos-RF, BidCos-Wired, System</param>
        /// <param name="sUrl">target URL of the XMLRPC Server</param>
        /// <param name="sCustomerId">InterfaceID to Identify the Interface, "" to stop sync</param>
        /// <param name="SessionID"></param>
        /// <param name="CCUIP">external CCU IP</param>
        /// <param name="Port">80</param>
        /// <param name="Username"></param>
        /// <param name="Password"></param>
        /// <returns>true = success</returns>
        public bool InitCGI(string Interface, string sUrl, string sCustomerId, string SessionID, string CCUIP, int Port, bool bSSL)
        {
            //_session_id_ interface url interfaceId 
            //Interface.init
            //Interface = BidCos-RF, BidCos-Wired, System

            if (string.IsNullOrEmpty(SessionID))
            {
                return false;
            }
            string sJSON = "{ \"method\": \"Interface.init\",\"params\": { \"_session_id_\":\"" + SessionID +
                "\",\"interface\":\"" + Interface +
                "\",\"url\":\"" + sUrl +
                "\",\"interfaceId\":\"" + sCustomerId + "\"}}";
            try
            {
                string sResult = PostJSON(Encoding.UTF8.GetBytes(sJSON), Port, CCUIP, bSSL);

                if (sResult.Contains("\"result\": true,\"error\": null"))
                    return true;
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            return false;
        }

        [WebMethod]
        public bool InitCGIStart(string Token)
        {
            if (oDB.Customers.Count(t => t.customerid == Token) > 0)
            {
                HMConfig oHMConf = oDB.HMConfig.First(t => t.customerid == Token);
                string sSessionID = GetSessionID(oHMConf.customerid);
                //string sSessionID = GetSessionID_CGI(oHMConf.external_ip, oHMConf.tcpport, oHMConf.username, oHMConf.password);
                if (string.IsNullOrEmpty(sSessionID))
                    return false;
                bool b1 = InitCGI("BidCos-RF", Properties.Settings.Default.XmlRpcUrl + "?id=" + Token + "&port=2001", Token, sSessionID, oHMConf.external_ip, oHMConf.tcpport, oHMConf.ssl);
                bool b2 = InitCGI("BidCos-Wired", Properties.Settings.Default.XmlRpcUrl + "?id=" + Token + "&port=2000", Token, sSessionID, oHMConf.external_ip, oHMConf.tcpport, oHMConf.ssl);
                //bool b3 = InitCGI("SYSTEM", Properties.Settings.Default.XmlRpcUrl + "?id=" + Token + "&port=2002", Token, sSessionID, oHMConf.external_ip, oHMConf.tcpport);
                if (b1 & b2)
                    return true;
                else
                    return false;
            
            }

            return false;
        }

        [WebMethod]
        public bool InitCGIStop(string Token)
        {
            if (oDB.Customers.Count(t => t.customerid == Token) > 0)
            {
                HMConfig oHMConf = oDB.HMConfig.First(t => t.customerid == Token);
                string sSessionID = GetSessionID(oHMConf.customerid);
                if (string.IsNullOrEmpty(sSessionID))
                    return false;
                bool b1 = InitCGI("BidCos-RF", Properties.Settings.Default.XmlRpcUrl + "?id=" + Token + "&port=2001", "", sSessionID, oHMConf.external_ip, oHMConf.tcpport, oHMConf.ssl);
                bool b2 = InitCGI("BidCos-Wired", Properties.Settings.Default.XmlRpcUrl + "?id=" + Token + "&port=2000", "", sSessionID, oHMConf.external_ip, oHMConf.tcpport, oHMConf.ssl);
                //bool b3 = InitCGI("SYSTEM", Properties.Settings.Default.XmlRpcUrl + "?id=" + Token + "&port=2002", "", sSessionID, oHMConf.external_ip, oHMConf.tcpport);
                if (b1 & b2)
                    return true;
                else
                    return false;

            }

            return false;
        }

        /// <summary>
        /// Import detailData from CCU into DB
        /// </summary>
        /// <param name="DetailData">return string from 'GetDeviceDetailsFromCCU' method</param>
        /// <param name="CustomerID"></param>
        public void ImportDeviceData(string DetailData, string CustomerID)
        {
            //Add Device data...
            /*
            foreach (string sLine in DetailData.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries))
            {
                DeviceDetails oDetails = new DeviceDetails();
                foreach (string sSetting in sLine.Split(';'))
                {
                    try
                    {
                        if (!sSetting.Contains('='))
                            continue;
                        switch (sSetting.Split('=')[0].ToUpper())
                        {
                            case "ADDRESS":
                                oDetails.address = sSetting.Split('=')[1];
                                break;
                            case "CHANNEL_TYPE":
                                oDetails.channel_type = sSetting.Split('=')[1];
                                break;
                            case "DEVICE_TYPE":
                                oDetails.device_type = sSetting.Split('=')[1];
                                break;
                            case "INTERFACE":
                                oDetails.@interface = sSetting.Split('=')[1];
                                break;
                            case "NAME":
                                oDetails.name = sSetting.Split('=')[1];
                                break;
                            case "VISIBLE":
                                oDetails.visible = Boolean.Parse(sSetting.Split('=')[1]);
                                break;
                            case "READABLE":
                                oDetails.readable = Boolean.Parse(sSetting.Split('=')[1]);
                                break;
                            case "WRITABLE":
                                oDetails.writable = Boolean.Parse(sSetting.Split('=')[1]);
                                break;
                            case "ROOMS":
                                int istart = sLine.IndexOf("ROOMS={", 0) + 7;
                                int iend = sLine.IndexOf("};", istart);
                                string sr = sLine.Substring(istart, iend - istart);
                                AddRooms(sr.Split(';'), oDetails.address, CustomerID);
                                break;
                            case "FUNCTIONS":
                                istart = sLine.IndexOf("FUNCTIONS={", 0) + 11;
                                iend = sLine.IndexOf("};", istart);
                                sr = sLine.Substring(istart, iend - istart);
                                AddFunctions(sr.Split(';'), oDetails.address, CustomerID);
                                break;

                        }
                    }
                    catch (Exception ex)
                    {
                        ex.Message.ToString();
                    }
                }

                try
                {
                    oDetails.customerid = CustomerID;
                    if (oDB.DeviceDetails.Count(t => t.address == oDetails.address & t.channel_type == oDetails.channel_type & t.customerid == CustomerID) > 0)
                    {
                        //Already exists
                        DeviceDetails oExistDetails = new DeviceDetails();
                        oExistDetails = oDB.DeviceDetails.First(t => t.address == oDetails.address & t.channel_type == oDetails.channel_type & t.customerid == CustomerID);
                        if (oExistDetails.name != oDetails.name)
                        {
                            oExistDetails.name = oDetails.name;
                            oDB.SaveChanges();
                        }
                    }
                    else
                    {

                        oDetails.id = CustomerID + DateTime.Now.Ticks.ToString();
                        oDB.DeviceDetails.Add(oDetails);
                        oDB.SaveChanges();
                    }
                }
                catch (Exception Ex)
                {
                    Ex.Message.ToString();
                }

            }*/
        }

        public Boolean CheckCustomerID(string CustomerID)
        {
            try
            {
                if (oDB.Customers.Count(t => t.customerid == CustomerID) > 0)
                    return true;
                else
                    return false;
            }
            catch(Exception ex)
            {
                ex.Message.ToString();
            }

            return false;
        }

        [WebMethod]
        public void NewSessionIDAsync(string CustomerID)
        {
            string sResult = "";
            try
            {
                HMConfig oHMConf = oDB.HMConfig.First(t => t.customerid == CustomerID);
                if (oHMConf.sessionexpdate == null)
                {
                    oHMConf.sessionexpdate = new DateTimeOffset(2014, 1, 1, 15, 00, 0, new TimeSpan(1, 0, 0));
                    oDB.SaveChangesAsync();
                }
                if (oHMConf.sessionexpdate > DateTime.Now)
                    return;
                else
                {
                    string sJSON = PostJSON(Encoding.UTF8.GetBytes("{ \"method\": \"Session.login\", \"params\":  { \"username\" : \"" + oHMConf.username + "\", \"password\" : \"" + oHMConf.password + "\" }}"), oHMConf.tcpport, oHMConf.external_ip, oHMConf.ssl);
                    sResult = sJSON.Split(',')[1].Split(':')[1].Replace("\"", "").Trim();
                    oHMConf.ccusessiontoken = sResult;
                    oHMConf.sessionexpdate = DateTime.Now + new TimeSpan(0, 0, oHMConf.sessiontimeout - 5);
                    oDB.SaveChangesAsync();
                }
            }
            catch { }
        }

        public string GetSessionID(string CustomerID)
        {
            string sResult = "";
            try
            {
                HMConfig oHMConf = oDB.HMConfig.First(t => t.customerid == CustomerID);
                if (oHMConf.sessionexpdate == null)
                    oHMConf.sessionexpdate = new DateTimeOffset(2014, 1, 1, 15, 00, 0, new TimeSpan(1, 0, 0));
                if (oHMConf.sessionexpdate > DateTime.Now)
                    return oHMConf.ccusessiontoken;
                else
                {
                    string sJSON = PostJSON(Encoding.UTF8.GetBytes("{ \"method\": \"Session.login\", \"params\":  { \"username\" : \"" + oHMConf.username + "\", \"password\" : \"" + oHMConf.password + "\" }}"), oHMConf.tcpport, oHMConf.external_ip, oHMConf.ssl);
                    sResult = sJSON.Split(',')[1].Split(':')[1].Replace("\"", "").Trim();
                    oHMConf.ccusessiontoken = sResult;
                    oHMConf.sessionexpdate = DateTime.Now + new TimeSpan(0, 0, oHMConf.sessiontimeout - 5);
                    oDB.SaveChanges();
                }
            }
            catch { }
            return sResult;
        }

        public string _GetSessionID_CGI(string CCUIP, int Port, string Username, string Password)
        {
            string sResult = "";
            try
            {
                if (string.IsNullOrEmpty(Username))
                    Username = "Admin";
                string sJSON = PostJSON(Encoding.UTF8.GetBytes("{ \"method\": \"Session.login\", \"params\":  { \"username\" : \"" + Username + "\", \"password\" : \"" + Password + "\" }}"), Port, CCUIP, false);
                sResult = sJSON.Split(',')[1].Split(':')[1].Replace("\"", "").Trim();
            }
            catch { }
            return sResult;
        }

        public bool ImportDevices_CGI(string SessionID, string CustomerID, string CCUIP, int Port, string Username, string Password, bool SSL)
        {
            bool bResult = true;
            if (string.IsNullOrEmpty(SessionID))
            {
                SessionID = GetSessionID(CustomerID);
            }

            try
            {
                string sJSON = PostJSON(Encoding.UTF8.GetBytes("{ \"method\": \"Device.listAll\", \"params\": { \"_session_id_\" : \"" + SessionID + "\" }}"), Port, CCUIP, SSL);
                Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(sJSON);
                foreach (Newtonsoft.Json.Linq.JToken jDevice in jObject["result"].Children())
                {
                    try
                    {
                        string sRes1 = DevicesGet_CGI(SessionID, jDevice.ToString(), CCUIP, Port, CustomerID);
                        importDevicesJSON(CustomerID, sRes1);
                        sRes1.ToString();
                    }
                    catch { bResult = false; }
                }
                //sResult = sJSON.Substring(sJSON.IndexOf('[') + 1, sJSON.IndexOf(']') - sJSON.IndexOf('[')).Replace("\"", "").Trim(' ').Split(',');
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                bResult = false;
            }

            return bResult;
        }

        [WebMethod]
        public bool ImportDevices(string Token)
        {
            if (oDB.HMConfig.Count(t => t.customerid == Token) > 0)
            {
                HMConfig oHMConf = oDB.HMConfig.First(t => t.customerid == Token);
                return ImportDevices_CGI("", oHMConf.customerid, oHMConf.external_ip, oHMConf.tcpport, oHMConf.username, oHMConf.password, oHMConf.ssl);
            }

            return false;
        }

        [WebMethod]
        public bool ImportRooms(string Token)
        {
            if (oDB.HMConfig.Count(t => t.customerid == Token) > 0)
            {
                HMConfig oHMConf = oDB.HMConfig.First(t => t.customerid == Token);
                return RoomsGet_CGI("", oHMConf.customerid, oHMConf.external_ip, oHMConf.tcpport, oHMConf.username, oHMConf.password);
            }

            return false;
        }

        [WebMethod]
        public bool ImportFunctions(string Token)
        {
            if (oDB.HMConfig.Count(t => t.customerid == Token) > 0)
            {
                HMConfig oHMConf = oDB.HMConfig.First(t => t.customerid == Token);
                return FunctionsGet_CGI("", oHMConf.customerid, oHMConf.external_ip, oHMConf.tcpport, oHMConf.username, oHMConf.password);
            }

            return false;
        }

        public bool importDevicesJSON(string CustomerID, string JSONString)
        {
            bool bResult = true;
            //string sInput = "{\"version\": \"1.1\",\"result\": {\"id\":\"6461\",\"name\":\"Ankleide Bewegungsmelder\",\"address\":\"HEQ0404597\",\"interface\":\"BidCos-RF\",\"type\":\"HM-Sec-MDIR\",\"channels\":[{\"id\":\"6481\",\"name\":\"Ankleide Bewegungsmelder\",\"address\":\"HEQ0404597:1\",\"deviceId\":\"6461\",\"index\":1,\"partnerId\":\"\",\"mode\":\"MODE_DEFAULT\",\"category\":\"CATEGORY_SENDER\",\"isReady\":true,\"isUsable\":true,\"isVisible\":true,\"isLogged\":false,\"isLogable\":true,\"isReadable\":true,\"isWritable\":false,\"isEventable\":true,\"isAesAvailable\":true,\"isVirtual\":false,\"channelType\":\"MOTION_DETECTOR\"}]},\"error\": null}";
            try
            {
                Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(JSONString);

                string sid = jObject["result"]["id"].ToString();
                string sname = jObject["result"]["name"].ToString();
                string saddress = jObject["result"]["address"].ToString();
                string sinterface = jObject["result"]["interface"].ToString();
                string stype = jObject["result"]["type"].ToString();

                dbEntities1 oDB = new dbEntities1();
                Devices oDevice = new Devices() { id = int.Parse(sid), Address = saddress, CustomerID = CustomerID, Interface = sinterface, Name = sname, Type = stype, C__createdAt = DateTime.Now };
                if (oDB.Devices.Count(t => t.CustomerID == CustomerID & t.Address == oDevice.Address) == 0)
                {
                    oDB.Devices.Add(oDevice);
                    oDB.SaveChanges();
                }


                foreach (Newtonsoft.Json.Linq.JToken jChannel in jObject["result"]["channels"].Children())
                {
                    try
                    {
                        Channels oChannel = new Channels()
                        {
                            id = int.Parse(jChannel["id"].ToString()),
                            Address = jChannel["address"].ToString(),
                            Category = jChannel["category"].ToString(),
                            ChannelType = jChannel["channelType"].ToString(),
                            CustomerId = CustomerID,
                            DeviceID = int.Parse(sid),
                            Index = int.Parse(jChannel["index"].ToString()),
                            Mode = jChannel["mode"].ToString(),
                            Name = jChannel["name"].ToString(),
                            IsAesAvailable = bool.Parse(jChannel["isAesAvailable"].ToString()),
                            IsEventable = bool.Parse(jChannel["isEventable"].ToString()),
                            IsLogable = bool.Parse(jChannel["isLogable"].ToString()),
                            IsLogged = bool.Parse(jChannel["isLogged"].ToString()),
                            IsReadable = bool.Parse(jChannel["isReadable"].ToString()),
                            IsReady = bool.Parse(jChannel["isReady"].ToString()),
                            IsUsable = bool.Parse(jChannel["isUsable"].ToString()),
                            IsVirtual = bool.Parse(jChannel["isVirtual"].ToString()),
                            IsVisible = bool.Parse(jChannel["isVisible"].ToString()),
                            IsWritable = bool.Parse(jChannel["isWritable"].ToString()),
                            C__createdAt = DateTime.Now

                        };
                        if (oDB.Channels.Count(t => t.CustomerId == CustomerID & t.Address == oChannel.Address) == 0)
                        {
                            oDB.Channels.Add(oChannel);
                            oDB.SaveChanges();
                        }
                    }
                    catch
                    {
                        bResult = false;
                    }
                }
            }
            catch
            { 
                bResult = false;
            }

            return bResult;
        }

        public string DevicesGet_CGI(string SessionID, string DeviceID, string CCUIP, int Port, string CustomerID)
        {
            if (string.IsNullOrEmpty(SessionID))
            {
                SessionID = GetSessionID(CustomerID);
            }

            string sResult = "";
            try
            {
                string sJSON = PostJSON(Encoding.UTF8.GetBytes("{ \"method\": \"Device.get\", \"params\": { \"_session_id_\" : \"" + SessionID + "\" , \"id\" : \"" + DeviceID + "\"}}"), Port, CCUIP, false);

                sResult = sJSON;
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            return sResult;
        }

        public bool RoomsGet_CGI(string SessionID, string CustomerID, string CCUIP, int Port, string Username, string Password)
        {
            bool bResult = true;
            if (string.IsNullOrEmpty(SessionID))
            {
                SessionID = GetSessionID(CustomerID);
            }

            try
            {
                string sJSON = PostJSON(Encoding.UTF8.GetBytes("{ \"method\": \"Room.getAll\", \"params\": { \"_session_id_\" : \"" + SessionID + "\"}}"), Port, CCUIP, false);
                Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(sJSON);
                dbEntities1 oDB = new dbEntities1();
                foreach (Newtonsoft.Json.Linq.JToken jRoom in jObject["result"].Children())
                {
                    try
                    {
                        Rooms oRoom = new Rooms()
                        {
                            CustomerId = CustomerID,
                            id = int.Parse(jRoom["id"].ToString()),
                            Description = jRoom["description"].ToString(),
                            Name = jRoom["name"].ToString(),
                            C__createdAt = DateTime.Now
                        };
                        if (oDB.Rooms.Count(t => t.CustomerId == CustomerID & t.id == oRoom.id) == 0)
                        {
                            oDB.Rooms.Add(oRoom);
                            oDB.SaveChanges();
                        }
                        foreach (string vID in jRoom["channelIds"].Values<string>())
                        {
                            try
                            {
                                RoomMapping oRoomMap = new RoomMapping() { ChannelId = int.Parse(vID), CustomerId = CustomerID, RoomId = oRoom.id, C__createdAt = DateTime.Now };
                                if (oDB.RoomMapping.Count(t => t.CustomerId == CustomerID & t.ChannelId == oRoomMap.ChannelId & t.RoomId == oRoomMap.RoomId) == 0)
                                {
                                    oDB.RoomMapping.Add(oRoomMap);
                                    oDB.SaveChanges();
                                }
                            }
                            catch { bResult = false; }
                        }

                    }
                    catch { bResult = false; }
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            return bResult;
        }

        public bool FunctionsGet_CGI(string SessionID, string CustomerID, string CCUIP, int Port, string Username, string Password)
        {
            bool bResult = true;
            if (string.IsNullOrEmpty(SessionID))
            {
                SessionID = GetSessionID(CustomerID);
            }

            try
            {
                string sJSON = PostJSON(Encoding.UTF8.GetBytes("{ \"method\": \"Subsection.getAll\", \"params\": { \"_session_id_\" : \"" + SessionID + "\"}}"), Port, CCUIP, false);
                Newtonsoft.Json.Linq.JObject jObject = Newtonsoft.Json.Linq.JObject.Parse(sJSON);
                dbEntities1 oDB = new dbEntities1();
                foreach (Newtonsoft.Json.Linq.JToken jFunction in jObject["result"].Children())
                {
                    try
                    {
                        Functions oFunction= new Functions()
                        {
                            CustomerId = CustomerID,
                            id = int.Parse(jFunction["id"].ToString()),
                            Description = jFunction["description"].ToString(),
                            Name = jFunction["name"].ToString(),
                            C__createdAt = DateTime.Now
                        };
                        if (oDB.Rooms.Count(t => t.CustomerId == CustomerID & t.id == oFunction.id) == 0)
                        {
                            oDB.Functions.Add(oFunction);
                            oDB.SaveChanges();
                        }
                        foreach (string vID in jFunction["channelIds"].Values<string>())
                        {
                            try
                            {
                                FunctionMapping oFunctionMap = new FunctionMapping() { ChannelId = int.Parse(vID), CustomerId = CustomerID, FunctionId = oFunction.id, C__createdAt = DateTime.Now };
                                if (oDB.RoomMapping.Count(t => t.CustomerId == CustomerID & t.ChannelId == oFunctionMap.ChannelId & t.RoomId == oFunctionMap.FunctionId) == 0)
                                {
                                    oDB.FunctionMapping.Add(oFunctionMap);
                                    oDB.SaveChanges();
                                }
                            }
                            catch { bResult = false; }
                        }

                    }
                    catch { bResult = false; }
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            return bResult;
        }

        [WebMethod]
        public bool SetValue(string SessionID, string Interface, string Address, string ValueKey, string sType, string sValue, string CustomerID)
        {
            if (string.IsNullOrEmpty(SessionID))
            {
                SessionID = GetSessionID(CustomerID);
            }
            if (string.IsNullOrEmpty(SessionID))
                return false;

            string sJSON = "{ \"method\": \"Interface.setValue\", \"params\": { \"_session_id_\" : \"" + SessionID +
                "\" , \"interface\" : \"" + Interface +
                "\" , \"address\" : \"" + Address +
                "\" , \"valueKey\" : \"" + ValueKey +
                "\" , \"type\" : \"" + sType +
                "\" , \"value\" : \"" + sValue + "\"}}";
            try
            {
                HMConfig oHMConf = oDB.HMConfig.First(t => t.customerid == CustomerID);

                string sResult = PostJSON(Encoding.UTF8.GetBytes(sJSON), oHMConf.tcpport, oHMConf.external_ip, oHMConf.ssl);

                if (sResult.Contains("\"result\": true,\"error\": null"))
                    return true;
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
            }
            return false;
        }

        public static bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        public static string Post(byte[] postBytes, int port, string TargetIP)
        {
            string result = "";

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://" + TargetIP + ":" + port.ToString());
            webRequest.Timeout = 3000;
            webRequest.Method = "POST";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.ContentLength = postBytes.Length;

            Stream postStream = webRequest.GetRequestStream();
            postStream.WriteTimeout = 3000;
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            Stream responseStream = webResponse.GetResponseStream();
            StreamReader responseStreamReader = new StreamReader(responseStream);
            result = responseStreamReader.ReadToEnd();
            webResponse.Close();
            responseStream.Close();

            return result;
        }

        public static string PostJSON(byte[] postBytes, int port, string TargetIP, bool SSL)
        {
            System.Net.ServicePointManager.Expect100Continue = false;
            string result = "";
            HttpWebRequest webRequest;
            if (SSL)
            {
                webRequest = (HttpWebRequest)WebRequest.Create("https://" + TargetIP + ":" + port.ToString() + "/api/homematic.cgi");
                ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications);
            }
            else
            {
                webRequest = (HttpWebRequest)WebRequest.Create("http://" + TargetIP + ":" + port.ToString() + "/api/homematic.cgi");
            }
            webRequest.Timeout = 15000;
            webRequest.Method = "POST";
            webRequest.ContentType = "application/json";
            webRequest.ContentLength = postBytes.Length;




            Stream postStream = webRequest.GetRequestStream();
            postStream.WriteTimeout = 15000;
            postStream.Write(postBytes, 0, postBytes.Length);
            postStream.Close();

            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            Stream responseStream = webResponse.GetResponseStream();
            StreamReader responseStreamReader = new StreamReader(responseStream);
            result = responseStreamReader.ReadToEnd();

            webResponse.Close();
            responseStream.Close();

            return result;
        }
    }
}
